import {
	getHotKeywordsData,
	getSearchGoodsData
} from "../../api/search";
export default {
	namespaced: true,
	state: {
		// 搜索的关键词
		keywords: "",
		//历史搜索关键词
		historyKeywords: uni.getStorageSync("historyKeywords") ? JSON.parse(uni.getStorageSync("historyKeywords")) : [],
		//热门搜索关键词
		hotKeywords: [],
		searchGoods: [] //搜索到的菜品的数据
	},
	mutations: {
		//设置搜索关键词
		["SET_KEYWORDS"](state, payload) {
			state.keywords = payload.keywords;
		},
		//设置历史搜索关键词
		["SET_HISTORY_KEYWORDS"](state, payload) {
			if (payload.keywords) {
				for (let i = 0; i < state.historyKeywords.length; i++) {
					if (state.historyKeywords[i] == payload.keywords) {
						state.historyKeywords.splice(i--, 1);
						break;
					}
				}
				//向数组开头添加元素
				state.historyKeywords.unshift(payload.keywords);
				//保存搜索关键词到缓存中
				uni.setStorageSync("historyKeywords", JSON.stringify(state.historyKeywords))
			}
		},
		//清除历史关键词
		["CLEAR_HISTORY_KEYWORDS"](state) {
			state.historyKeywords = [];
			uni.removeStorageSync("historyKeywords");
		},
		//设置热门搜索关键词
		["SET_HOT_KEYWORDS"](state, payload) {
			state.hotKeywords = payload.hotKeywords;
		},
		//设置搜索菜品的数据
		["SET_SEARCH_GOODS"](state, payload) {
			state.searchGoods = payload.searchGoods;
		},
		//设置搜索菜品的分页数据
		["SET_SEARCH_GOODS_PAGE"](state, payload) {
			state.searchGoods.push(...payload.searchGoods);
		}
	},
	actions: {
		// 定义获取热门关键词方法
		getHotKeywords(conText, payload) {
			getHotKeywordsData().then(res => {
				if (res.code == 200) {
					conText.commit("SET_HOT_KEYWORDS", {
						hotKeywords: res.data
					});
				} else {
					conText.commit("SET_HOT_KEYWORDS", {
						hotKeywords: []
					});
				}
			})
		},
		//获取搜索的菜品
		getSearchGoods(conText, payload) {
			getSearchGoodsData(payload).then(res => {
				if (res.code == 200) {
					conText.commit("SET_SEARCH_GOODS", {
						searchGoods: res.data
					});
					if (payload.success) {
						payload.success(parseInt(res.pageinfo.pagenum));
					}
				} else {
					conText.commit("SET_SEARCH_GOODS", {
						searchGoods: []
					});
				}
			})
		},
		//获取搜索菜品分页数据
		getSearchGoodsPage(conText, payload) {
			getSearchGoodsData(payload).then(res => {
				if (res.code == 200) {
					conText.commit("SET_SEARCH_GOODS_PAGE", {
						searchGoods: res.data
					});
				}
			})
		}

	}
}